<?php
class HomeAction extends CommonAction{
    public function index(){
		@$page = $this->_get('page');
		if(!intval($page))
			$page=1;
		$team = new TeamModel($this->_get('id'),$page);
		if(!$team->teamid)
			echo '<script>window.history.back(-1);</script>';
		$this->assign('info',$team->info);				//团队信息显示
		$this->assign('pollnum',$team->pollnum);				//团队信息显示
		$this->assign('memmber',$team->memmber);		//成员列表的显示
		$this->assign('memmberlist',$team->memmberlist);		//成员列表的显示
		$this->assign('teamteacher',$team->teamteacher);//指导老师
		$this->assign('Identity',$team->Identity);		//识别访客身份  1.队长进入自己的主页 2.队员进入自己的主页 3.队长进入别人的团队页 4。队员进入别人的团队页 5.游客
		$this->assign('projectInfo',$team->projectInfo);//团队参赛方案
		$this->assign('problemInfo',$team->problemInfo);//商业实践问题
		$this->assign('pagenum',$team->pagenum);		//总页数
		$this->assign('page',$team->page);				//当前页
		$this->display('index');
    }
	
	//只有队长可以修改，其余人只能看
	public function teamEdit(){
		//判断是否是队长
		$db = M('Team');
		$team = $db->where('Id='.$this->_get('id'))->find();
		if($_SESSION[C('USER_AUTH_KEY')]['UserId'] == $team['Captain']){
			$this->assign('captain',1);
		}else{
			$this->assign('captain',-1);
		}
		$this->assign('team',$team);
		$this->display();
	}
	//修改团队信息
	public function teamInfoMod(){
		//判断是否有上传Logo
		if(!empty($_FILES['Logo']['name'])){
			import('ORG.Net.UploadFile');
			$upload = new UploadFile();// 实例化上传类
			$upload->maxSize  = 1024000 ;// 设置附件上传大小1M
			$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
			$upload->savePath =  './UpFile/Img/TeamFace/';// 设置附件上传目录
			//设置需要生成缩略图，仅对图像文件有效
			$upload->thumb = true;
			// 设置引用图片类库包路径
			$upload->imageClassPath = 'ORG.Util.Image';
			//设置需要生成缩略图的文件后缀
			$upload->thumbPrefix = 'logo_';  //产生1张缩略图
			//设置缩略图最大宽度
			$upload->thumbMaxWidth = '120';
			//设置缩略图最大高度
			$upload->thumbMaxHeight = '120';
			//设置上传文件规则
			$upload->saveRule = uniqid;
			//删除原图
			$upload->thumbRemoveOrigin = true;
			if(!$upload->upload()){
				// 上传错误提示错误信息
				$this->error($upload->getErrorMsg());
			}else{
				// 上传成功 获取上传文件信息
				$info = $upload->getUploadFileInfo();
				$_POST['Logo'] = 'logo_'.$info[0]['savename'];
			}
		}
		$db = M('Team');
		//获取旧图
		$team = $db->where('Id='.$this->_post('id'))->find();
		$oldimg = $team['Logo'];
		$db->create();
		$res = $db->where('Id='.$this->_post('id'))->save();
		if($res){
			//删除旧图
			unlink('UpFile/Img/TeamFace/'.$oldimg);
			$this->success('修改信息成功！');
		}else{
			$this->error('团队信息修改失败或没有信息被修改！');
		}
	}
	//接收加入参赛队申请 
	public function joinTeam(){
		$id = $this->_get("id");
		$apply = M('Teammembers');
		$count = $apply->where('IsApproved=1 AND TeamId = '.$id )->count(); 
		if($count<5){
			$isagree=1;
			$Data = M('Team');
			$list = $Data->where('Id ='.$id)->find();
			$this->assign('list',$list);
			$this->assign("isagree",$isagree);
			
			$res=M()->query('select Id from teammembers where IsApproved=0 and TeamId='.$id.' and UserId='.$_SESSION[C('USER_AUTH_KEY')]['UserId']);
			// dump($res);
			if($res){
				echo '<script>closewindoe(true,true)</script>';
				return false;
			}else{
				$this->display(); // 输出模板			
			}
		}else{
			$isagree=0;
			echo '<script>closewindoe(true,null)</script>';
		}
	}

	//团队搜索
		public function searchTeam(){
		//友情团队页最新团队显示
		$team = new CreatTeamModel();
		$this->assign('newteam',$team->newteam);//团队信息显示;

		$Data = M('Team'); // 实例化Data数据对象
    	import('ORG.Util.Page');// 导入分页类
    	$where = '';
    	$map['Name'] =array('like',array('%'.$_POST['TeamName'].'%'));
    	$map['SchoolName'] =array('like',array('%'.$_POST['School'].'%'));
    	if($_POST['MatchStatus'] != 0){
    	$map['Status'] = array('eq',$_POST['MatchStatus']);
    	}
    	$count = $Data->where($map)->count();// 查询满足要求的总记录数 $map表示查询条件;
    	$Page = new Page($count,4);// 实例化分页类 传入总记录数
    	$show = $Page->show();// 分页显示输出
		$res = M()->query('SELECT u.TrueName,u.UserId
							FROM team t,users u 
							where t.Captain=u.UserId');
		$this->assign('res',$res);
    	$list = $Data->where($map)->order('CraeteDate')->limit($Page->firstRow.','.$Page->listRows)->select();
    	$this->assign('list',$list);// 赋值数据集
    	$this->assign('page',$show);// 赋值分页输出
    	$this->display(); // 输出模板
	}

	//向团队管理员发送申请人请求
	public function applyTeam(){
			$id = $this->_get("id");
			$apply = M('Teammembers');
			$data['TeamId'] = $id;
			$data['UserId'] = $_SESSION[C('USER_AUTH_KEY')]['UserId'];
			$data['TrueName'] = $_SESSION[C('USER_AUTH_KEY')]['TrueName'];
			$data['Info'] = $this->_post('JoinInfo');
			$data['IsApproved'] = 0;
			$data['CreateDate'] = date("Y-m-d H:i:s");
			$teamname = $apply->add($data);
			//dump($data);
			if($teamname){
				// $this->success('O(∩_∩)O~提交成功，请等待管理员审核');
				 echo '<script>window.parent.callbackfun(true,null);</script>';
			}else{
				 echo '<script>window.parent.callbackfun(false,null);</script>';
				// $this->error('提交数据失败╮(╯▽╰)╭');
			}
			
	}
	
	//检测传入的get('id')
	public function checkgetid($id){
		if($idres=M()->query('select Id from team where Id= '.$id))
			return $id;
		else
			return false;
	}
	
	//团队成员
	public function teammember(){
		if($id=$this->myteamid()){
			$team = new TeamModel($id);
			$this->assign('list',$team->memmber);//成员列表的显示；
			$this->assign('info',$team->info);//团队信息显示;
			$this->display();			
		}else{
			echo '<script>noteamid();</script>';
		}
	}
	
	//团队成员列表
	public function teammenberlist(){
		if($id=$this->myteamid()){
			$team = new TeamModel($id);
			$this->assign('list',$team->memmberlist);//成员列表的显示；
			$this->assign('info',$team->info);//团队信息显示;
			$this->display();			
		}else{
			echo '<script>noteamid();</script>';
		}
	}
	
	//删除团队中的成员。Ajax请求的。
	public function delteammember(){
		$Id=$this->_post('memberid');
		$Model = new Model() ;
		$res = $Model->execute('delete from teammembers where Id='.$Id);
		if($res){
			echo 'true';
		}
	}
	
	//同意团队成员的申请
		public function approveteammember(){
		$Id=$this->_post('membersid');
		$Model = new Model() ;
		$res = $Model->execute('update teammembers set IsApproved=1 where Id='.$Id);
		if($res){
			echo json_encode(array('res'=>true,'msg'=>'纳入成员成功'));
			$toid = $Id;
			$title = '加入团队系统提示';
			$content = '恭喜您已经加入了团队！O(∩_∩)O~';
			tosendmail(0,$toid,$title,$content);
		}else{
			echo json_encode(array('res'=>false,'msg'=>'操作失败,请重试'));
		}
	}
	
	//查询团队队长的ID ---根据成员表的ＩＤ查询
	public function capationid($mbid){
		$team = M()->query('SELECT t.Captain FROM team t,teammembers tm where tm.Id = '.$mbid.' and tm.TeamId = t.Id');
		return $team[0]['Captain'];
	}
	
	//指导老师管理
	public function teamteacher(){
		$teamid=$this->myteamid();
		$list=M()->query('select Id,InstructorId,TrueName,CreateDate,IsApproved from teaminstructors where TeamId='.$teamid );
		$this->assign('list',$list);
		$this->display();
	}
	
	//返回团队队长所在的团队ID
	public function myteamid(){
		$myteam=M()->query('select Id from team where Captain= '.$_SESSION[C('USER_AUTH_KEY')]['UserId']);
		return $myteam[0]['Id'];
	}
	
	//删除团队中的指导教师。Ajax请求的。
	public function delteateacher(){
		$Id=$this->_post('teacherid');
		$Model = new Model() ;
		$res = $Model->execute('delete from teaminstructors where Id='.$Id);

		if($res){
			echo 'true';
		}
		
	}
	
	
	//人气投票支持
	public function addTeamVote(){
		$teamid=$this->_get('TeamId');
		$nowtime=date('Y-m-d H:i:s');
		$oldtime=date('Y-m-d H:i:s',time()-2*3600);
		$VoterId=$_SESSION[C('USER_AUTH_KEY')]['UserId'];
		if(M()->query('select * from teamvote where TeamId = '.$teamid.' and  VoterId='.$VoterId.' and  CreateDate >"'.$oldtime.'"')){
			$msg = '你距上一次为该团队的投票还不足两小时，请稍后再投！';
			$res = false;
		}else{
		 	if(M()->execute('insert into teamvote(Id,TeamId,VoterId,CreateDate,Version) values ( NULL,'.$teamid.','.$VoterId.',"'.$nowtime.'","1.0")')){
				$msg = '团队投票成功';
				$res = true;
				M('Team')->where('Id='.$teamid)->setInc('Poll');
				$pid = $this->_post('pid');
				if($pid){
					M('Project')->where('Id='.$pid)->setInc('Poll');
				}else{
					$res = M('Project')->where('TeamId='.$teamid)->find();
					if($res){
						M('Project')->where('Id='.$res['Id'])->setInc('Poll');
					}
				}
			}else{
				$msg = '团队投票失败';
				$res = false;
			}
		}
		echo json_encode(array('res'=>$res,'msg'=>$msg)); 
	}

	//加为友情团队
	public function addFriendTeam(){
		$id = $this->_post('id');	//被我邀请的团队的ID
		$myteamid=$this->getmyteamid();	//我的团队的ID
		
		$hasadd='select Id, IsApproved from friendlyteam where TeamId2='.$myteamid.' and TeamId1 = '.$id;
		if($hasaddres=M()->query($hasadd)){//对方已经发送过请求
			if($hasaddres[0]['IsApproved']==1){
				die(json_encode(array('res'=>false,'msg'=>'你们已经是友情团队了，就别再次发送请求。'))); 
			}else{
				M()->execute('update friendlyteam set IsApproved=1 where Id='.$hasaddres[0]['Id']);
				die(json_encode(array('res'=>true,'msg'=>'您与该团队都互相请求了，自动转为友情团队')));
			}
		}
		$sql1='select Id from friendlyteam where TeamId1='.$myteamid.' and TeamId2='.$id.' and IsApproved=1'; 	//查看是否已经是批准的好友团队
		$sql2='select Id from friendlyteam where TeamId1='.$myteamid.' and TeamId2='.$id.' and IsApproved=0';	//查看是否已经发送过请求
		$sql3='select Id from friendlyteam where TeamId1='.$myteamid.' and IsApproved=0';						
		if($res1 = M()->query($sql1)){
			$msg = ('你们已经是友情团队了，请勿再次发送请求。');
			$res = false;
			die(json_encode(array('res'=>$res,'msg'=>$msg))); 
		}
		if(count($res3 = M()->query($sql3))>=8){
			$msg = ('您发送的邀请成为友情团队次数已经超过8次，请勿再次发送请求。');
			$res = false;
			die(json_encode(array('res'=>$res,'msg'=>$msg))); 
		}
		if($res2 = M()->query($sql2)){
			$msg = ('您已经发送过请求了，请勿再次发送请求。');
			$res = false;
			die(json_encode(array('res'=>$res,'msg'=>$msg))); 
		}


		$add = M()->execute('
						INSERT into friendlyteam 
						set TeamId1='.$this->getmyteamid().',
						TeamId2='.$id.',
						IsApproved=0,
						Version=0
					');
		if($add){
			$msg = '已经发出请求，请等待队长审核';
			$res = true;
			die(json_encode(array('res'=>$res,'msg'=>$msg))); 
		}else{
			$msg = '发送请求失败。';
			$res = false;
			die(json_encode(array('res'=>$res,'msg'=>$msg))); 
		}

	}
	//获得团队的teamid
	private function getmyteamid(){
		$myid=$_SESSION[C('USER_AUTH_KEY')]['UserId'];
		$teaminfo=M()->query('select Id from team where Captain='.$myid);
		return $teaminfo[0]['Id'];
	}

	//我的友情团队
	public function listMyFriendlyTeam(){
		$list3 = M()->query('select ft.Id ,ft.TeamId1,ft.TeamId2, t.Name, t.Logo, t.CaptainName, t.Declaration, t.SchoolName
							from friendlyteam ft, team t
							where (( ft.TeamId1 ='.$this->getmyteamid().'  and ft.TeamId2=t.Id )
							or ( ft.TeamId2 ='.$this->getmyteamid().' and ft.TeamId1=t.Id )) and ft.IsApproved=1'
							);
		$this->assign('list',$list3);// 赋值数据集
		$this->display(); // 输出模板
	}


	//删除友情团队
	public function delMyFrienTeam(){
		$Id=$this->_post('fileid');
		
		$Model = new Model() ;
		$res = $Model->execute('delete from friendlyteam where Id='.$Id);

		if($res){
			echo 'true';
		}

	}


	//未审核的团队
	public function listInvitedTeam(){
		$list1 = M()->query('select ft.Id , t.Name, t.Logo, t.CaptainName, t.Declaration, t.SchoolName
							from friendlyteam ft, team t
							 where ft.TeamId2='.$this->_get('id').' and t.Id=ft.TeamId1 and ft.IsApproved=0'
							);
		$this->assign('list',$list1);// 赋值数据集
		$this->display(); // 输出模板
	}
	//删除未审核的团队
	public function delnocheckFrienTeam(){
		$Id=$this->_post('fileid');
		
		$Model = new Model() ;
		$res = $Model->execute('delete from friendlyteam where Id='.$Id);

		if($res){
			echo 'true';
		}

	}

	//我邀请的友情团队
	public function listInvitTeam(){
		$list2 = M()->query('select ft.Id , t.Name, t.Logo, t.CaptainName, t.Declaration, t.SchoolName
							from friendlyteam ft, team t
							 where ft.TeamId1='.$this->_get('id').' and t.Id=ft.TeamId2 and ft.IsApproved=0');
		$this->assign('list',$list2);// 赋值数据集
		$this->display(); // 输出模板
		
	}


	//删除我邀请的友情团队
	public function delMyInviteFrienTeam(){
		 $Id=$this->_post('fileid');
		
		$Model = new Model() ;
		$res = $Model->execute('delete from friendlyteam where Id='.$Id);

		if($res){
			echo 'true';
		}

	}

	//接受友情团队的邀请
	public function applyasfriendteam(){
		$applyid = $this->_post('fileid');
		$res = M()->execute('update friendlyteam set IsApproved=1 where Id='.$applyid);
		if($res){
			$this->ajaxReturn($this->_post(),'同意成功',1);
			$toid = $applyid;
			$title = '加入团队系统提示';
			$content = '恭喜你们成为友情团队O(∩_∩)O~';
			tosendmail(0,$toid,$title,$content);
		} 
	}

	//AJAX输出 参赛历程
	public function logload(){
		@$page = $this->_get('page');
		if(!intval($page))
			$page=1;
		$team = new TeamModel($this->_get('id'),$page);
		if(!$team->teamid)
			echo '<script>alert("非法操作");window.history.back(-1);</script>';
		$this->assign('teamlog',$team->teamlog);		//参赛历程
		$this->assign('pagenum',$team->pagenum);		//总页数
		$this->assign('page',$team->page);				//当前页
		$this->display();
	}


	//邀请教官和其他老师点评
	public function inviteOfficer(){
		//过滤非法操作
		$teamid = $this->_get('id');
		$cap = M('Team')->where('Id = '.$teamid.' and Captain='.$_SESSION[C('USER_AUTH_KEY')]['UserId'])->find();
		if(!$cap){
			echo '<script type="text/javascript">alert("非法操作");window.history.back();</script>';
		}
		import('ORG.Util.Page');// 导入分页类
		$user = M('Users');
		//UserType=4教官
		$count = $user->where('UserType=4 and IsApproved=1')->count();// 查询满足要求的总记录数
		$Page = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数
		$show = $Page->show();// 分页显示输出
		//进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$list = $user->where('UserType=4 and IsApproved=1')->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('list',$list);// 赋值数据集
		$this->assign('page',$show);// 赋值分页输出
		$this->display();
	}


	//邀请老师
	public function inviteTeacher(){
		//过滤非法操作
		$teamid = $this->_get('id');
		$cap = M('Team')->where('Id='.$teamid.' and Captain='.$_SESSION[C('USER_AUTH_KEY')]['UserId'])->find();
		if(!$cap){
			echo '<script type="text/javascript">alert("非法操作");window.history.back();</script>';
		}
		import('ORG.Util.Page');
		$user = M('Users');
		$count = $user->where('UserType=3 and IsApproved=1')->count();
		$Page = new Page($count,20);
		$show = $Page->show();
		$list = $user->where('UserType=3 and IsApproved=1')->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('list',$list);
		$this->assign('page',$show);
		$this->display();
	}
	
	//搜索指导老师
	public function searchTeacher(){
		import('ORG.Util.Page');
		$user = M('Users');
    	$map['TrueName'] =array('like',array('%'.$_POST['Name'].'%'));
    	$map['OrgName'] =array('like',array('%'.$_POST['School'].'%'));
		$map['UserType'] = 3;
		$map['IsApproved'] = 1;
		$count  = $user->where($map)->count();
		$Page = new Page($count,20);
		$show = $Page->show();
		$list = $user->where($map)->limit($Page->firstRow.','.$Page->listRows)->select();
		$res = M()->query('select u.UserId,t.PersonalIntroduce 
							from teacher t,users u where t.UserId=u.UserId ');
		$this->assign('res',$res);
    	$this->assign('list',$list);// 赋值数据集
		$this->assign('page',$show);
    	$this->display(); // 输出模板
	}
	//邀请指导老师
	public function inviteSeachTeacher(){
		$myteamid=$this->getmyteamid();//teamid 
		$userid = $this->_post('userid'); //userid
		$truename = M('users')->where('UserId='.$userid)->find();
		$res = M('teaminstructors')->where('TeamId='.$myteamid.' and InstructorId='.$userid)->select();
		if($res){
			$this->ajaxReturn($this->_post(),'您已邀请过了，请勿重复邀请!',-1);
		}else{
			$result = M('teaminstructors')->where('TeamId='.$myteamid)->select();
			if(count($result) == 2){
				$this->ajaxReturn($this->_post(),'您的团队只能邀请2名指导老师',-1);
			}else{
				//准备插入数据库
				$data['TeamId'] = $myteamid;
				$data['InstructorId'] = $userid;
				$data['IsApproved'] = 0;
				$data['CreateDate'] = date('Y-m-d H:i:s');
				$data['TrueName'] = $truename['TrueName'];
				
				if(M('teaminstructors')->add($data)){
					$this->ajaxReturn($this->_post(),'邀请成功',1);
					$toid = $userid;
					$title = '加入团队系统提示';
					$content = '恭喜您邀请教师成功！O(∩_∩)O~';
					tosendmail(0,$toid,$title,$content);
					
				}else{
					$this->ajaxReturn($this->_post(),'邀请失败,请重试',-1);
				}
			}
		}
	}
	//被邀请的教官及其他老师列表
	public function invite(){
		import('ORG.Util.Page');
		$project = M('Project')->where('TeamId='.$this->_get('id'))->find();
		$count = M()->query("select count(*) num from projectcommentlimit pcl,projectcomment pc where pc.UserId=pcl.UserId and pcl.ProjectId=".$project['Id']);
		$page = new Page($count[0]['num'],10);
		$show = $page->show();
		$this->assign('page',$show);
		$list = M()->limit($page->firstRow.','.$page->listRows)->query("select pc.UserName,pc.Content from projectcommentlimit pcl,projectcomment pc where pc.UserId=pcl.UserId and pcl.ProjectId=".$project['Id']);
		$this->assign('list',$list);
		$this->display();
	}
	

	//邀请指导老师
	public function doinvite(){
		//判断是否提交了参赛项目/方案--projectid
		$teamid = $this->_post('teamid');
		$userid = $this->_post('userid');
		$project = M('Project')->where('TeamId='.$teamid)->find();
		if(!$project){
			$this->ajaxReturn($this->_post(),'邀请失败，你还没有提交参赛方案!',-1);
		}
		//判断是否已邀请
		$res = M('Projectcommentlimit')->where('userid='.$userid)->find();
		if($res){
			$this->ajaxReturn($this->_post(),'你已邀请过了，请勿重复邀请!',-1);
		}
		//准备插入数据库
		$data['UserId'] = $userid;
		$data['ProjectId'] = $project['Id'];
		if(M('Projectcommentlimit')->add($data)){
			$this->ajaxReturn($this->_post(),'邀请成功',1);
		}else{
			$this->ajaxReturn($this->_post(),'邀请失败,请重试',-1);
		}
	}
	//团队博客管理
	public function teamBlog(){
		$teamid = $this->_get('id');
		//$list = M('Teamblogs')->where('TeamId='.$teamid)->select();
		import('ORG.Util.Page');
		$count = M('')->query("select count(*) num from teamblogs t,bloglog b where t.BlogId=b.Id and t.TeamId=".$teamid);
		$page = new Page($count[0]['num'],5);
		$show = $page->show();
		$this->assign('page',$show);
		$list = M('')->limit($page->firstRow.','.$page->listRows)->query("select t.Id,t.IsApproved,b.Id,b.Title,b.TrueName,b.CreateDate from teamblogs t,bloglog b where t.BlogId=b.Id and t.TeamId=".$teamid);
		$this->assign('list',$list);
		$this->display('teamblog');
	}
	//删除团队博文
	public function delTeamBlog(){
		$id = $this->_post('id');
		$res = M('Teamblogs')->where('BlogId='.$id)->delete();
		if($res){
			$this->ajaxReturn($id,'删除成功',1);
		}else{
			$this->ajaxReturn($id,'删除失败',-1);
		}
	}
	//通过团队博文setField//IsApproved
	public function passTeamBlog(){
		$id = $this->_post('id');
		$res = M('Teamblogs')->where('BlogId='.$id)->setField('IsApproved',1);
		if($res){
			$this->ajaxReturn($id,'审核通过！',1);
		}else{
			$this->ajaxReturn($id,'审核失败！',-1);
		}
	}

	public function friend(){
		$team = new CreatTeamModel();
		$this->assign('newteam',$team->newteam);//团队信息显示;
		$this->display();
	}
}